package org.grow.swimming.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.grow.swimming.dao.MaterialInfoRepo;
import org.grow.swimming.dto.MaterialInfoQC;
import org.grow.swimming.dto.PagedResults;
import org.grow.swimming.entity.MaterialInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: xwg
 * @CreateDate: 2022/5/8
 */

@RestController
@RequestMapping("/swimming/material")
public class MaterialController {
    @Autowired
    private MaterialInfoRepo materialInfoRepo;
    @Autowired
    private ObjectMapper objectMapper;


    @PostMapping("/insert")
    public MaterialInfo insert(@RequestBody MaterialInfo materialInfo) {
        return materialInfoRepo.save(materialInfo);
    }

    @PostMapping("/query")
    public PagedResults<MaterialInfo> query(@RequestBody MaterialInfoQC materialInfoQC) {

        Integer pageNum = materialInfoQC.getPageNum();
        Integer pageSize = materialInfoQC.getPageSize();
        String materialKeyWord = materialInfoQC.getMaterialKeyWord();

        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "suggestPrice"));
        Page<MaterialInfo> page = materialInfoRepo.findAll(((root, query, criteriaBuilder) -> {
            /*
            *     private String materialCode;

                    private String materialLabel;
            * */
            Predicate conjunction = criteriaBuilder.conjunction();
            List<Expression<Boolean>> predicates = conjunction.getExpressions();
            if (StringUtils.hasText(materialKeyWord)) {
                Predicate one = criteriaBuilder.like(root.get("materialCode"), "%" + materialKeyWord + "%");
                Predicate two = criteriaBuilder.like(root.get("materialLabel"), "%" + materialKeyWord + "%");
                predicates.add(criteriaBuilder.or(one, two));
            }
            return conjunction;


        }), pageRequest);
        try {
            System.out.println(objectMapper.writeValueAsString(page));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new PagedResults<>(page.getTotalElements(), page.getContent());

    }

}
